package com.jt;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;

import java.io.IOException;

/**
 * @author 张琪
 * @date 2020/12/12
 * @describe
 */
public class testHttpClient {

    /**
     * 1. 实例化HttpClient
     * 2. 定义URL地址
     * 3. 定义请求对象
     * 4. 发起HttpClient请求
     * 5. 获得响应结果
     */


    @Test
    public void testGet() throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        String url = "http://www.baidu.com";
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
//            正常情况
            HttpEntity httpEntity = httpResponse.getEntity();
            String result = EntityUtils.toString(httpEntity);
            System.out.println(result);
        } else {
//            其他情况
            System.err.println("请求数据有误");
        }
    }
}
